<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 添加按钮 -->
      <el-row>
        <el-col><el-button type="primary" @click="addDialogVisible = true">添加角色</el-button></el-col>
      </el-row>
      <!-- 添加角色对话框 -->
      <el-dialog title="添加用户" @close="addDialogClosed" :visible.sync="addDialogVisible" width="50%">
        <!-- 对话框按钮区域 -->
        <span slot="footer" class="dialog-footer">
          <!-- 表单区 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息对话框 -->
      <el-dialog @close="editDialogClosed" title="修改角色信息" :visible.sync="editDialogVisible" width="50%">
        <el-form :model="editForm" ref="editFormRef" label-width="70px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色列表区 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column width="50px" type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1 === 0 ? 'bdtop':'', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!--一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套 渲染二级和三级权限 -->
                <el-row :class="[i2 === 0 ? 'bdtop' : '' , 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id" >
                  <el-col :span="6">
                    <!-- 二级权限 -->
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag  type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑角色信息按钮 -->
            <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!-- 删除角色按钮 -->
            <el-button @click="removeRoleById(scope.row.id)" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button @click="showSetRightDialog(scope.row)" type="warning" icon="el-icon-setting" size="mini">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" ref="treeRef" show-checkbox :props="rightsProps" node-key="id" :default-checked-keys="defKeys" default-expand-all="true"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignRights ">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取用户列表数据
      queryInfo: {
        query: ''
      },
      // 所有角色列表数据
      roleList: [],
      // 展示分配权限的对话框
      setRightDialogVisible: false,
      // 所有权限数据
      rightsList: [],
      // 当前分配权限角色的ID
      roleId: '',
      // 树形控件的属性绑定对象
      rightsProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点ID值数组
      defKeys: [],
      // 展示添加角色的对话框
      addDialogVisible: false,
      // 添加角色表单数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 监听修改角色信息对话框的事件
      editDialogVisible: false,
      // 查询到的角色信息
      editForm: {},
      // 添加角色表单规则对象
      addFormRules: {
        roleName: [{
          required: true,
          message: '请输入角色名',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 8,
          message: '角色名长度必须在2~8个字符之间',
          trigger: 'blur'
        }],
        roleDesc: {
          min: 2,
          max: 50,
          message: '请输入角色描述，2~50个字符',
          trigger: 'blur'
        }
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$msg.error('获取用户列表失败！')
      }
      this.roleList = res.data
    },
    // 添加角色
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$msg.error('非法添加')
        // 发送添加角色请求
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$msg.error('添加角色失败')
        }
        // 成功
        this.$msg.success('添加角色成功')
        // 关闭对话框
        this.addDialogVisible = false
        // 刷新角色列表数据
        this.getRoleList()
      })
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改角色对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 弹出修改角色信息对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$msg.error('获取角色信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 对表单信息进行预验证后提交
    editRoleInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$msg.error('内容不合法，请检查后再提交！')
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        if (res.meta.status !== 200) {
          this.$msg.error('修改角色信息失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 重新获取角色信息数据
        this.getRoleList()
        // 提示信息
        this.$msg.success('修改用户信息成功！')
      })
    },
    // 删除角色信息
    async removeRoleById (id) {
      const cnofirmResult = await this.$confirm('确定删除该角色信息吗?不可恢复', '请谨慎操作!', {
        confirmButtonText: '确定删除',
        cancelButtonText: '我点错了',
        type: 'warning'
      }).catch(err => err)
      // 如果确认删除则返回值为confirm字符串
      // 如果取消删除则返回值为cancel字符串
      if (cnofirmResult !== 'confirm') {
        return this.$msg.info('已取消操作')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$msg.error('删除角色信息失败！')
      }
      this.$msg.success('删除角色成功！')
      this.getRoleList()
    },
    // 根据ID删除对应的权限
    async removeRightById (role, rightId) {
      // 提示信息
      const cnofirmResult = await this.$confirm('确定撤销该权限吗?', '请谨慎操作!', {
        confirmButtonText: '继续撤销',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (cnofirmResult !== 'confirm') {
        return this.$msg.info('已取消操作')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$msg.error('删除角色信息失败！')
      }
      this.$msg.success('删除角色成功！')
      role.children = res.data
    },
    // 展示分配权限对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$msg.error('获取权限数据失败')
      }
      // 把获取到的数据保存到data中
      this.rightsList = res.data
      // 清空上一个defkeys中的数据
      this.defKeys = []
      // 递归获取三级节点的ID
      this.getLeafKeys(role, this.defKeys)
      // 显示对话框
      this.setRightDialogVisible = true
    },
    // 通过递归的形式获取所有角色下三级权限的id，并存储到defKeys中
    getLeafKeys (node, arr) {
      if (!node.children) {
        // 若果当前节点不包含children属性则是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 分配权限操作
    async assignRights () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$msg.error('分配权限失败')
      }
      // 成功提示
      this.$msg.success('分配权限成功')
      // 重新获取列表数据
      this.getRoleList()
      // 关闭对话框
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
